﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

using SlUser = SmartSpace.UI.Silverlight.Web.Models.User;
using SmartSpace.Core;
using System.Web.Security;
using SlField = SmartSpace.UI.Silverlight.Web.Metadatas.FieldMetadata;
using SlNavigation = SmartSpace.UI.Silverlight.Web.Models.Navigation;
using SlModule = SmartSpace.UI.Silverlight.Web.Models.AppModule;
using SlView = SmartSpace.UI.Silverlight.Web.Models.ModuleView;
using SlApplication = SmartSpace.UI.Silverlight.Web.Models.Application;
using SlShortcut = SmartSpace.UI.Silverlight.Web.Models.Shortcut;
using SmartSpace.Data;
using SmartSpace.Workflow;

namespace SmartSpace.UI.Silverlight.Web
{
    /// <summary>
    /// Summary description for FrameworkWebService
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class FrameworkWebService : System.Web.Services.WebService
    {
        #region 认证

        /// <summary>
        /// 检查是否已认证
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public SingleResult<SlUser> CheckAuthenticated()
        {
            if (User == null || !User.Identity.IsAuthenticated)
            {
                return new SingleResult<SlUser>(false, "没有认证!", null);
            }
            else
            {
                ICoreService service = Global.Get<ICoreService>();
                User user = service.FindUser(this.User.Identity.Name);
                if (user != null)
                {
                    SlUser userModel = new SlUser();
                    userModel.Account = user.Account;
                    userModel.Name = user.Name;
                    FormsAuthentication.SetAuthCookie(user.Account, false);
                    return new SingleResult<SlUser>(true, "认证成功!", userModel);
                }
                else
                {
                    FormsAuthentication.SignOut();
                    return new SingleResult<SlUser>(false, "没有认证!", null);
                }
            }
        }

        /// <summary>
        /// 帐号密码认证
        /// </summary>
        /// <param name="authenticateModel">用户认证模型</param>
        /// <returns></returns>
        [WebMethod]
        public SingleResult<SlUser> Authenticate(string account, string password)
        {
            ICoreService service = Global.Get<ICoreService>();
            User user = service.FindUser(this.User.Identity.Name);
            if (user != null)
            {
                SlUser userModel = new SlUser();
                userModel.Account = user.Account;
                userModel.Name = user.Name;
                FormsAuthentication.SetAuthCookie(user.Account, false);
                return new SingleResult<SlUser>(true, "认证成功!", userModel);
            }
            else
            {
                FormsAuthentication.SignOut();
                return new SingleResult<SlUser>(false, "没有认证!", null);
            }
        }

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        [WebMethod]
        public ServiceResult SignOut()
        {
            FormsAuthentication.SignOut();

            return new ServiceResult(true, "注销成功!");
        }

        #endregion

        #region 导航

        [WebMethod]
        public ListResult<SlNavigation> GetNavigations(string username, Guid applicationId)
        {
            List<SlNavigation> slNavigations = new List<SlNavigation>();

            ICoreService service = Global.Get<ICoreService>();
            User user = service.FindUser(username);
            if (user != null)
            {
                List<Navigation> navigations = service.FindNavigations(applicationId);
                foreach (var item in navigations)
                {
                    slNavigations.Add(ConvertNavigation(item));
                }
                return new ListResult<SlNavigation>(true, "获取成功!", slNavigations);
            }
            else
            {
                return new ListResult<SlNavigation>(false, "获取失败!", null);
            }
        }

        private SlNavigation ConvertNavigation(Navigation navigation)
        {
            SlNavigation slNavigation = new SlNavigation();
            slNavigation.ID = navigation.Id;
            slNavigation.Name = navigation.Caption;
            slNavigation.ViewArguments = navigation.Arguments;
            slNavigation.Children = new List<SlNavigation>();

            if (navigation.ViewId != null && navigation.ViewId.Value!=Guid.Empty)
            {
                slNavigation.View = new SlView();
                slNavigation.View.ID = navigation.ViewId.Value;

                ICoreService coreService = Global.Get<ICoreService>();
                List<Module> modules = coreService.FindModules(0, 999);
                foreach (var module in modules)
                {
                    foreach (var view in module.Views)
                    {
                        if (view.Id == navigation.ViewId)
                        {
                            slNavigation.View.Name = view.Name;
                            slNavigation.View.Type = view.Name;
                            slNavigation.View.ModuleID = module.Id;
                            break;
                        }
                    }

                    if (slNavigation.View.ModuleID != default(Guid))
                    {
                        break;
                    }
                }
            }

            if (navigation.Children != null && navigation.Children.Count > 0)
            {
                foreach (var item in navigation.Children)
                {
                    slNavigation.Children.Add(ConvertNavigation(item));
                }
            }
            return slNavigation;
        }

        #endregion
        
        #region 获取快捷方式

        [WebMethod]
        public ListResult<SlShortcut> GetShortcuts(string account, Guid applicationId)
        {
            return new ListResult<SlShortcut>(true, "Success", new List<SlShortcut>());
        }
        #endregion

        #region 应用程序信息

        [WebMethod]
        public ListResult<SlApplication> GetApplications(string userName)
        {
            ICoreService service = Global.Get<ICoreService>();
            List<Application> apps = service.FindApplications();

            List<SlApplication> slApps = new List<SlApplication>();
            foreach (var app in apps)
            {
                SlApplication slApp = new SlApplication();
                slApp.ID = app.Id;
                slApp.Name = app.Name;
                slApp.IconPath = "http://localhost:12310/Handlers/res.ashx?id=" + app.Id.ToString("N");
                slApp.ProxyUser = CheckAuthenticated().Data;
                slApp.Order = app.OrderIndex;

                slApp.ThemeID = app.Theme.Name;// "SmartSpace.UI.Silverlight.Themes.Fashtion";
                slApp.ThemeName = app.Theme.Caption;// "Fashtion主题";
                slApp.ThemePath = app.Theme.Package;// "./Themes/Fashtion/SmartSpace.UI.Silverlight.Themes.Fashtion.dll";
                slApp.ThemeVersion = "1.0.0.0";

                Navigation defaultNavigation = service.FindDefaultNavigation(app.Id);
                if (defaultNavigation != null)
                {
                    slApp.DefaultNavigationID = service.FindDefaultNavigation(app.Id).Id;
                }

                slApps.Add(slApp);
            }

            return new ListResult<SlApplication>(true, "Success!", slApps);
        }

        #endregion

        #region 模块信息

        [WebMethod]
        public ListResult<SlModule> GetModules(Guid applicationId)
        {
            List<SlModule> slModules = new List<SlModule>();

            ICoreService coreService = Global.Get<ICoreService>();
            List<Module> modules = coreService.FindModules(applicationId);
            foreach (var module in modules)
            {
                SlModule slModule = new SlModule();
                slModule.ID = module.Id;
                slModule.Name = module.Caption;
                slModule.Type = module.Name;
                slModule.Assembly = module.Package;
                slModule.Views = new List<Models.ModuleView>();

                foreach (var view in module.Views)
                {
                    SlView slView = new SlView();
                    slView.ID = view.Id;
                    slView.Name = view.Name;
                    slView.Type = view.Name;
                    slModule.Views.Add(slView);
                }

                slModules.Add(slModule);
            }
            return new ListResult<SlModule>(true, "获取成功!", slModules);
        }

        #endregion
    }
}
